<template>
  <el-container>
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" label-width="100px">
        <el-form-item label="分类名" prop="type_name">
          <el-input v-model="form.model.type_name" placeholder="请输入分类名称（建议5字以内）"></el-input>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button
        v-if="modal.params.type == 'add'"
        v-auth="'shop.admin.attr.shop_type.list'"
        type="primary"
        @click="confirm"
        >添加</el-button
      >
      <el-button
        v-if="modal.params.type == 'edit'"
        type="primary"
        @click="confirm"
        >更新</el-button
      >
    </el-footer>
  </el-container>
</template>
<script setup>
  import { cloneDeep } from 'lodash';
  import { onMounted, reactive, ref, unref } from 'vue';
  import { ElMessage } from 'element-plus'
  import { api } from './goods.service';
  const emit = defineEmits(['modalCallBack']);
  const props = defineProps({
    modal: {
      type: Object,
    },
  });
  // 添加 编辑 form
  let formRef = ref(null);
  const form = reactive({
    model: {
      type_name: '',
    },
    template:{
      types: {
        type_name: "", // 分类名称/服务名称
        icon_url: "", // 图标utl
        parent_id: "0", // 父级id
        remake: "" // 备注
      }
    },
    rules: {
      type_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
    },
  });
  const loading = ref(false);
  // 获取详情
  async function getDetail(id) {
    loading.value = true;
    const { error, data } = await api.service.detail(id);
    error === 0 && (form.model = data);
    loading.value = false;
  }
  // 表单关闭时提交
  async function confirm() {
    unref(formRef).validate(async (valid) => {
      if (!valid) return;
      form.template.types.type_name = form.model.type_name
      let fromData = cloneDeep(form.template);
      const { error } = 
        props.modal.params.type == 'add'
          ? await api.service.addType(fromData)
          : await api.service.editType(fromData);
      if (error == 0) {
        ElMessage({
          message: '操作成功',
          type: 'success',
        })
        emit('modalCallBack', { event: 'confirm' });
      }
    });
  }
  async function init() {
    if (props.modal.params.id) {
      await getDetail(props.modal.params.id);
    }
  }
  onMounted(() => {
    // init();
    if(props.modal.params.type == 'edit'){
      form.template = cloneDeep(props.modal.params.data)
    }
    
  });
</script>
